"""cos对象存储"""

from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from django.conf import settings
from qcloud_cos.cos_exception import CosServiceError

# 创建对象存储的桶
def create_cos_bucket(bucket, region='ap-shanghai'):
    # 替换为用户的 secretId(登录访问管理控制台获取)
    # 替换为用户的 secretKey(登录访问管理控制台获取)
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY,
                       Scheme='https')

    client = CosS3Client(config)

    response = client.create_bucket(
        Bucket=bucket,
        ACL="public-read"  # private  /  public-read / public-read-write
    )

    # 跨域问题解决
    cors_config = {
        'CORSRule': [
            {
                'AllowedOrigin': '*',
                'AllowedMethod': ['GET', 'PUT', 'HEAD', 'POST', 'DELETE'],
                'AllowedHeader': "*",
                'ExposeHeader': "*",
                'MaxAgeSeconds': 500
            }
        ]
    }

    client.put_bucket_cors(
        Bucket=bucket,
        CORSConfiguration=cors_config
    )


# 对象存储-上传文件
def upload_cos_file(region, bucket, file_obj, key):
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY,
                       Scheme='https')
    client = CosS3Client(config)
    # upload_file_from_buffer 这个方法可以上传文件对象
    response = client.upload_file_from_buffer(
        Bucket=bucket,
        Body=file_obj,  # 文件对象
        Key=key,  # 上传到桶之后的文件名
    )

    return 'https://%s.cos.%s.myqcloud.com/%s' % (bucket, region, key)


# 删除cos对象存储中的单个文件
def delete_cos_file(region, bucket, key):
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY,
                       Scheme='https')
    client = CosS3Client(config)

    response = client.delete_object(
        Bucket=bucket,
        Key=key,  # 文件名
    )


# 批量删除多个对象
def delete_cos_objects(region, bucket, key_list):
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY,
                       Scheme='https')
    client = CosS3Client(config)

    response = client.delete_objects(
        Bucket=bucket,
        Delete=key_list,  # 批量删除的key列表
    )


# 获取临时凭证
def get_cos_credential(bucket, region):
    # 生成一个临时凭证，并给前端返回
    # 1. 安装一个生成临时凭证python模块   pip install -U qcloud-python-sts
    # 2. 写代码
    from sts.sts import Sts
    config = {
        # 临时密钥有效时长，单位是秒（30分钟=1800秒）
        'duration_seconds': 1800,
        # 固定密钥 id
        'secret_id': settings.TENCENT_COS_ID,
        # 固定密钥 key
        'secret_key': settings.TENCENT_COS_KEY,
        # 换成你的 bucket
        'bucket': bucket,
        # 换成 bucket 所在地区
        'region': region,
        # 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径
        # 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
        'allow_prefix': '*',
        # 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
        'allow_actions': [
            #  简单上传操作
            "name/cos:PutObject",
            # 'name/cos:PostObject',
            # 'name/cos:DeleteObject',
            # "name/cos:UploadPart",
            # "name/cos:UploadPartCopy",
            # "name/cos:CompleteMultipartUpload",
            # "name/cos:AbortMultipartUpload",
            # "*",
        ],

    }
    sts = Sts(config)
    result_dict = sts.get_credential()
    return result_dict


# 删除桶操作

def delete_bucket(bucket, region):
    # 删除桶中所有文件
    # 删除桶中所有碎片
    # 删除桶
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY,
                       Scheme='https')
    client = CosS3Client(config)
    files_objects = client.list_objects(bucket)
    try:
        # 找出桶中所有的文件
        while True:
            files_objects = client.list_objects(bucket)
            # 已经删除完毕，获取不到值
            contents = files_objects.get('Contents')
            if not contents:
                break
            # 批量删除
            objects = {
                "Quiet": "true",
                "Object": [{"Key": item["Key"]} for item in contents]
            }
            client.delete_objects(bucket, objects)
            if files_objects['IsTruncated'] == 'false':
                break

        # 找到碎片删除
        while True:
            part_uploads = client.list_multipart_uploads(bucket)
            uploads = part_uploads.get('Upload')
            if not uploads:
                break
            for item in uploads:
                client.abort_multipart_upload(bucket, item['Key'], item['UploadId'])
            if files_objects['IsTruncated'] == 'false':
                break

        # 删除桶
        client.delete_bucket(bucket)
    except CosServiceError:
        pass
